<!DOCTYPE html>
	<html>
	<head>
	<meta charset="utf-8">
	<title>菜鸟教程(runoob.com)</title>
	</head>
	<body>
	 
	<h1>我的第一个标题</h1>
	 


















<pre>



	




PHPExcel Developer Documentation




	
1.Contents
PHPExcel Developer Documentation	1
1.	Contents
Contents
PHPExcel Developer Documentation	1
1.	Contents	2
2.	Prerequisites	5
2.1.	Software requirements	5
2.2.	Installation instructions	5
2.3.	Getting started	5
2.4.	Useful links and tools	5
2.4.1.	OpenXML / SpreadsheetML	5
2.4.2.	Frequently asked questions	6
2.4.3.	Tutorials	7
3.	Architecture	8
3.1.	Schematical	8
3.2.	Lazy Loader	8
3.3.	Spreadsheet in memory	8
3.4.	Readers and writers	8
3.5.	Fluent interfaces	9
4.	Creating a spreadsheet	11
4.1.	The PHPExcel class	11
4.1.1.	Loading a Workbook from a file	11
4.1.2.	Creating a new workbook	11
4.2.	Configuration Settings	11
4.2.1.	Cell Caching	11
4.2.2.	Language/Locale	13
4.3.	Clearing a Workbook from memory	14
4.4.	Worksheets	14
4.4.1.	Adding a new Worksheet	15
4.4.2.	Copying Worksheets	15
4.4.3.	Removing a Worksheet	15
4.5.	Accessing cells	16
4.5.1.	Setting a cell value by coordinate	16
4.5.2.	Setting a range of cells from an array	18
4.5.3.	Retrieving a cell by coordinate	20
4.5.4.	Setting a cell value by column and row	20
4.5.5.	Retrieving a cell by column and row	20
4.5.6.	Looping cells	21
4.5.7.	Using value binders to facilitate data entry	22
4.6.	PHPExcel recipes	22
4.6.1.	Setting a spreadsheet’s metadata	23
4.6.2.	Setting a spreadsheet’s active sheet	23
4.6.3.	Write a date or time into a cell	23
4.6.4.	Write a formula into a cell	24
4.6.5.	Locale Settings for Formulae	25
4.6.6.	Write a newline character "\n" in a cell (ALT+"Enter")	25
4.6.7.	Explicitly set a cell’s datatype	26
4.6.8.	Change a cell into a clickable URL	26
4.6.9.	Setting a worksheet’s page orientation and size	26
4.6.10.	Page Setup: Scaling options	26
4.6.11.	Page margins	27
4.6.12.	Center a page horizontally/vertically	28
4.6.13.	Setting the print header and footer of a worksheet	28
4.6.14.	Setting printing breaks on a row or column	30
4.6.15.	Show/hide gridlines when printing	30
4.6.16.	Setting rows/columns to repeat at top/left	30
4.6.17.	Specify printing area	30
4.6.18.	Formatting cells	30
4.6.19.	Number formats	32
4.6.20.	Alignment and wrap text	32
4.6.21.	Setting the default style of a workbook	33
4.6.22.	Styling cell borders	33
4.6.23.	Conditional formatting a cell	34
4.6.24.	Add a comment to a cell	35
4.6.25.	Apply autofilter to a range of cells	35
4.6.26.	Setting security on a spreadsheet	35
4.6.27.	Setting data validation on a cell	36
4.6.28.	Setting a column’s width	37
4.6.29.	Show/hide a column	37
4.6.30.	Group/outline a column	37
4.6.31.	Setting a row’s height	38
4.6.32.	Show/hide a row	38
4.6.33.	Group/outline a row	38
4.6.34.	Merge/unmerge cells	38
4.6.35.	Inserting rows/columns	39
4.6.36.	Add a drawing to a worksheet	39
4.6.37.	Reading Images from a worksheet	39
4.6.38.	Add rich text to a cell	40
4.6.39.	Define a named range	40
4.6.40.	Redirect output to a client’s web browser	41
4.6.41.	Setting the default column width	42
4.6.42.	Setting the default row height	42
4.6.43.	Add a GD drawing to a worksheet	42
4.6.44.	Setting worksheet zoom level	42
4.6.45.	Sheet tab color	42
4.6.46.	Creating worksheets in a workbook	42
4.6.47.	Hidden worksheets (Sheet states)	43
4.6.48.	Right-to-left worksheet	43
5.	Performing formula calculations	44
5.1.	Using the PHPExcel calculation engine	44
5.2.	Known limitations	45
5.2.1.	Operator precedence	45
5.2.2.	Formulas involving numbers and text	45
6.	Reading and writing to file	46
6.1.	PHPExcel_IOFactory	46
6.1.1.	Creating PHPExcel_Reader_IReader using PHPExcel_IOFactory	46
6.1.2.	Creating PHPExcel_Writer_IWriter using PHPExcel_IOFactory	46
6.2.	Excel 2007 (SpreadsheetML) file format	47
6.2.1.	PHPExcel_Reader_Excel2007	47
6.2.2.	PHPExcel_Writer_Excel2007	47
6.3.	Excel 5 (BIFF) file format	48
6.3.1.	PHPExcel_Reader_Excel5	48
6.3.2.	PHPExcel_Writer_Excel5	49
6.4.	Excel 2003 XML file format	49
6.4.1.	PHPExcel_Reader_Excel2003XML	49
6.5.	Symbolic LinK (SYLK)	50
6.5.1.	PHPExcel_Reader_SYLK	50
6.6.	Open/Libre Office (.ods)	51
6.6.1.	PHPExcel_Reader_OOCalc	51
6.7.	CSV (Comma Separated Values)	51
6.7.1.	PHPExcel_Reader_CSV	51
6.7.2.	PHPExcel_Writer_CSV	52
6.8.	HTML	53
6.8.1.	PHPExcel_Reader_HTML	53
6.8.2.	PHPExcel_Writer_HTML	53
6.9.	PDF	55
6.9.1.	PHPExcel_Writer_PDF	55
6.10.	Generating Excel files from templates (read, modify, write)	56
7.	Credits	58
Appendix A:	Valid array keys for style applyFromArray()	59

	

2.Prerequisites
2.1.Software requirements
The following software is required to develop using PHPExcel:
»PHP version 5.2.0 or newer
»PHP extension php_zip enabled *)
»PHP extension php_xml enabled
»PHP extension php_gd2 enabled (if not compiled in)

*) php_zip is only needed by PHPExcel_Reader_Excel2007, PHPExcel_Writer_Excel2007 and PHPExcel_Reader_OOCalc. In other words, if you need PHPExcel to handle .xlsx or .ods files you will need the zip extension, but otherwise not.
You can remove this dependency for writing Excel2007 files (though not yet for reading) by using the PCLZip library that is bundled with PHPExcel. See the FAQ section of this document (2.4.2) for details about this. PCLZip does have a dependency on PHP’s zlib extension being enabled.
2.2.Installation instructions
Installation is quite easy: copy the contents of the Classes folder to any location within your application source directories.

Example:
If your web root folder is /var/www/ you may want to create a subfolder called /var/www/Classes/ and copy the files into that folder so you end up with files:

/var/www/Classes/PHPExcel.php
/var/www/Classes/PHPExcel/Calculation.php
/var/www/Classes/PHPExcel/Cell.php
...
2.3.Getting started
A good way to get started is to run some of the tests included in the download.

Copy the "Examples" folder next to your "Classes" folder from above so you end up with:
/var/www/ Examples/01simple.php
/var/www/ Examples/02types.php
...

Start running the tests by pointing your browser to the test scripts:
http://example.com/ Examples/01simple.php
http://example.com/ Examples/02types.php
...

Note: It may be necessary to modify the include/require statements at the beginning of each of the test scripts if your "Classes" folder from above is named differently.

2.4.Useful links and tools
There are some links and tools which are very useful when developing using PHPExcel. Please refer to the PHPExcel CodePlex pages for an update version of the list below.
2.4.1.OpenXML / SpreadsheetML
»File format documentation
http://www.ecma-international.org/news/TC45_current_work/TC45_available_docs.htm

»OpenXML Explained e-book
http://openxmldeveloper.org/articles/1970.aspx 

»Microsoft Office Compatibility Pack for Word, Excel, and PowerPoint 2007 File Formats
http://www.microsoft.com/downloads/details.aspx?familyid=941b3470-3ae9-4aee-8f43-c6bb74cd1466&displaylang=en

»OpenXML Package Explorer
http://www.codeplex.com/PackageExplorer/
2.4.2.Frequently asked questions
The up-to-date F.A.Q. page for PHPExcel can be found on http://www.codeplex.com/PHPExcel/Wiki/View.aspx?title=FAQ&referringTitle=Requirements.
There seems to be a problem with character encoding...
It is necessary to use UTF-8 encoding for all texts in PHPExcel. If the script uses different encoding then you can convert those texts with PHP's iconv() or mb_convert_encoding() functions.
PHP complains about ZipArchive not being found
Make sure you meet all requirements, especially php_zip extension should be enabled.

The ZipArchive class is only required when reading or writing formats that use Zip compression (Excel2007 and OOCalc). Since version 1.7.6 the PCLZip library has been bundled with PHPExcel as an alternative to the ZipArchive class.

This can be enabled by calling:

PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);
before calling the save method of the Excel2007 Writer.

You can revert to using ZipArchive by calling:

PHPExcel_Settings::setZipClass(PHPExcel_Settings::ZIPARCHIVE);

At present, this only allows you to write Excel2007 files without the need for ZipArchive (not to read Excel2007 or OOCalc)
Excel 2007 cannot open the file generated by PHPExcel_Writer_2007 on Windows
“Excel found unreadable content in '*.xlsx'. Do you want to recover the contents of this workbook? If you trust the source of this workbook, click Yes.”

Some older versions of the 5.2.x php_zip extension on Windows contain an error when creating ZIP files. The version that can be found on http://snaps.php.net/win32/php5.2-win32-latest.zip should work at all times.

Alternatively, upgrading to at least PHP 5.2.9 should solve the problem.

If you can’t locate a clean copy of ZipArchive, then you can use the PCLZip library as an alternative when writing Excel2007 files, as described above.
Fatal error: Allowed memory size of xxx bytes exhausted (tried to allocate yyy bytes) in zzz on line aaa
PHPExcel holds an "in memory" representation of a spreadsheet, so it is restricted by PHP's memory limitations. The memory made available to PHP can be increased by editing the value of the memory_limit directive in your php.ini file, or by using ini_set('memory_limit', '128M') within your code (ISP permitting).

Some Readers and Writers are faster than others, and they also use differing amounts of memory. You can find some indication of the relative performance and memory usage for the different Readers and Writers, over the different versions of PHPExcel, on the discussion board.

If you've already increased memory to a maximum, or can't change your memory limit, then this discussion on the board describes some of the methods that can be applied to reduce the memory usage of your scripts using PHPExcel.
Protection on my worksheet is not working?
When you make use of any of the worksheet protection features (e.g. cell range protection, prohibiting deleting rows, ...), make sure you enable worksheet security. This can for example be done like this:

$objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);
Feature X is not working with PHPExcel_Reader_Y / PHPExcel_Writer_Z
Not all features of PHPExcel are implemented in all of the Reader / Writer classes. This is mostly due to underlying libraries not supporting a specific feature or not having implemented a specific feature.

For example autofilter is not implemented in PEAR Spreadsheet_Excel_writer, which is the base of our Excel5 writer.

We are slowly building up a list of features, together with the different readers and writers that support them, in the "Functionality Cross-Reference.xls" file in the /Documentation folder.
Formulas don’t seem to be calculated in Excel2003 using compatibility pack?
This is normal behaviour of the compatibility pack, Excel2007 displays this correctly. Use PHPExcel_Writer_Excel5 if you really need calculated values, or force recalculation in Excel2003.
Setting column width is not 100% accurate
Trying to set column width, I experience one problem. When I open the file in Excel, the actual width is 0.71 less than it should be. 

The short answer is that PHPExcel uses a measure where padding is included. See section: “Setting a column’s width” for more details.
How do I use PHPExcel with my framework
»There are some instructions for using PHPExcel with Joomla on the Joomla message board
»A page of advice on using PHPExcel in the Yii framework
»The Bakery has some helper classes for reading and writing with PHPExcel within CakePHP
»Integrating PHPExcel into Kohana http://www.flynsarmy.com/2010/07/phpexcel-module-for-kohana-3/ and Интеграция PHPExcel и Kohana Framework
»Using PHPExcel with Typo3
Joomla Autoloader interferes with PHPExcel Autoloader
Thanks to peterrlynch for the following advice on resolving issues between the PHPExcel autoloader and Joomla Autoloader

2.4.3.Tutorials
»English PHPExcel tutorial 
http://openxmldeveloper.org
»French PHPExcel tutorial
http://g-ernaelsten.developpez.com/tutoriels/excel2007/
»Russian PHPExcel Blog Postings
http://www.web-junior.net/sozdanie-excel-fajjlov-s-pomoshhyu-phpexcel/
»A Japanese-language introduction to PHPExcel http://journal.mycom.co.jp/articles/2009/03/06/phpexcel/index.html

3.Architecture
3.1.Schematical

3.2.Lazy Loader
PHPExcel implements an autoloader or “lazy loader”, which means that it is not necessary to include every file within PHPExcel. It is only necessary to include the initial PHPExcel class file, then the autoloader will include other class files as and when required, so only those files that are actually required by your script will be loaded into PHP memory. The main benefit of this is that it reduces the memory footprint of PHPExcel itself, so that it uses less PHP memory.

If your own scripts already define an autoload function, then this may be overwritten by the PHPExcel autoload function. For example, if you have:

function __autoload($class) {
    ...
}

Do this instead:

function myAutoload($class) {
    ...
}
spl_autoload_register('myAutoload');

Your autoloader will then co-exist with the autoloader of PHPExcel.
3.3.Spreadsheet in memory
PHPExcel’s architecture is built in a way that it can serve as an in-memory spreadsheet. This means that, if one would want to create a web based view of a spreadsheet which communicates with PHPExcel’s object model, he would only have to write the front-end code.

Just like desktop spreadsheet software, PHPExcel represents a spreadsheet containing one or more worksheets, which contain cells with data, formulas, images, …
3.4.Readers and writers
On its own, PHPExcel does not provide the functionality to read from or write to a persisted spreadsheet (on disk or in a database). To provide that functionality, readers and writers can be used.

By default, the PHPExcel package provides some readers and writers, including one for the Open XML spreadsheet format (a.k.a. Excel 2007 file format). You are not limited to the default readers and writers, as you are free to implement the PHPExcel_Writer_IReader and PHPExcel_Writer_IWriter interface in a custom class.


3.5.Fluent interfaces
PHPExcel supports fluent interfaces in most locations. This means that you can easily “chain” calls to specific methods without requiring a new PHP statement. For example, take the following code:

$objPHPExcel->getProperties()->setCreator("Maarten Balliauw");
$objPHPExcel->getProperties()->setLastModifiedBy("Maarten Balliauw");
$objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");
$objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document");
$objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");
$objPHPExcel->getProperties()->setKeywords("office 2007 openxml php");
$objPHPExcel->getProperties()->setCategory("Test result file");

This can be rewritten as:

$objPHPExcel->getProperties()
    ->setCreator("Maarten Balliauw")
    ->setLastModifiedBy("Maarten Balliauw")
    ->setTitle("Office 2007 XLSX Test Document")
    ->setSubject("Office 2007 XLSX Test Document")
    ->setDescription(
        "Test document for Office 2007 XLSX, generated using PHP classes."
    )
    ->setKeywords("office 2007 openxml php")
    ->setCategory("Test result file");


Using fluent interfaces is not required 
Fluent interfaces have been implemented to provide a convenient programming API. Use of them is not required, but can make your code easier to read and maintain. It can also improve performance, as you are reducing the overall number of calls to PHPExcel methods.










	
4.Creating a spreadsheet
4.1.The PHPExcel class
The PHPExcel class is the core of PHPExcel. It contains references to the contained worksheets, document security settings and document meta data.

To simplify the PHPExcel concept: the PHPExcel class represents your workbook.
Typically, you will create a workbook in one of two ways, either by loading it from a spreadsheet file, or creating it manually. A third option, though less commonly used, is cloning an existing workbook that has been created using one of the previous two methods.
4.1.1.Loading a Workbook from a file
Details of the different spreadsheet formats supported, and the options available to read them into a PHPExcel object are described fully in the “PHPExcel User Documentation - Reading Spreadsheet Files” document.


$inputFileName = './sampleData/example1.xls';

/** Load $inputFileName to a PHPExcel Object  **/
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);

4.1.2.Creating a new workbook
If you want to create a new workbook, rather than load one from file, then you simply need to instantiate it as a new PHPExcel object.


/** Create a new PHPExcel Object  **/
$objPHPExcel = new PHPExcel();


A new workbook will always be created with a single worksheet.
4.2.Configuration Settings
Once you have included the PHPExcel files in your script, but before instantiating a PHPExcel object or loading a workbook file, there are a number of configuration options that can be set which will affect the subsequent behaviour of the script.
4.2.1.Cell Caching
PHPExcel uses an average of about 1k/cell in your worksheets, so large workbooks can quickly use up available memory. Cell caching provides a mechanism that allows PHPExcel to maintain the cell objects in a smaller size of memory, on disk, or in APC, memcache or Wincache, rather than in PHP memory. This allows you to reduce the memory usage for large workbooks, although at a cost of speed to access cell data.
By default, PHPExcel still holds all cell objects in memory, but you can specify alternatives. To enable cell caching, you must call the PHPExcel_Settings::setCacheStorageMethod() method, passing in the caching method that you wish to use. 

$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_in_memory;
PHPExcel_Settings::setCacheStorageMethod($cacheMethod);

setCacheStorageMethod() will return a boolean true on success, false on failure (for example if trying to cache to APC when APC is not enabled).

A separate cache is maintained for each individual worksheet, and is automatically created when the worksheet is instantiated based on the caching method and settings that you have configured. You cannot change the configuration settings once you have started to read a workbook, or have created your first worksheet.

Currently, the following caching methods are available.

PHPExcel_CachedObjectStorageFactory::cache_in_memory;
The default. If you don’t initialise any caching method, then this is the method that PHPExcel will use. Cell objects are maintained in PHP memory as at present.
PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized;
Using this caching method, cells are held in PHP memory as an array of serialized objects, which reduces the memory footprint with minimal performance overhead.
PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;
Like cache_in_memory_serialized, this method holds cells in PHP memory as an array of serialized objects, but gzipped to reduce the memory usage still further, although access to read or write a cell is slightly slower.
PHPExcel_CachedObjectStorageFactory::cache_igbinary;
Uses PHP’s igbinary extension (if it’s available) to serialize cell objects in memory. This is normally faster and uses less memory than standard PHP serialization, but isn’t available in most hosting environments.
PHPExcel_CachedObjectStorageFactory::cache_to_discISAM;
When using cache_to_discISAM all cells are held in a temporary disk file, with only an index to their location in that file maintained in PHP memory. This is slower than any of the cache_in_memory methods, but significantly reduces the memory footprint. By default, PHPExcel will use PHP’s temp directory for the cache file, but you can specify a different directory when initialising cache_to_discISAM.
$cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_discISAM;
$cacheSettings = array( 'dir'  => '/usr/local/tmp'
                      );
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
The temporary disk file is automatically deleted when your script terminates.
PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
Like cache_to_discISAM, when using cache_to_phpTemp all cells are held in the php://temp I/O stream, with only an index to their location maintained in PHP memory. In PHP, the php://memory wrapper stores data in the memory: php://temp behaves similarly, but uses a temporary file for storing the data when a certain memory limit is reached. The default is 1 MB, but you can change this when initialising cache_to_phpTemp.
$cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp;
$cacheSettings = array( 'memoryCacheSize'  => '8MB'
                      );
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
The php://temp file is automatically deleted when your script terminates.
PHPExcel_CachedObjectStorageFactory::cache_to_apc;
When using cache_to_apc, cell objects are maintained in APC[ You must have APC enabled for PHP to use this option.] with only an index maintained in PHP memory to identify that the cell exists. By default, an APC cache timeout of 600 seconds is used, which should be enough for most applications: although it is possible to change this when initialising cache_to_APC.
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_APC;
$cacheSettings = array( 'cacheTime'        => 600
                      );
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
When your script terminates all entries will be cleared from APC, regardless of the cacheTime value, so it cannot be used for persistent storage using this mechanism.
PHPExcel_CachedObjectStorageFactory::cache_to_memcache
When using cache_to_memcache, cell objects are maintained in memcache[ You must have a memcache server running, and have enabled memcache for your PHP to use this option.] with only an index maintained in PHP memory to identify that the cell exists.
By default, PHPExcel looks for a memcache server on localhost at port 11211. It also sets a memcache timeout limit of 600 seconds. If you are running memcache on a different server or port, then you can change these defaults when you initialise cache_to_memcache:
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_memcache;
$cacheSettings = array( 'memcacheServer'  => 'localhost',
                        'memcachePort'    => 11211,
                        'cacheTime'       => 600
                      );
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
When your script terminates all entries will be cleared from memcache, regardless of the cacheTime value, so it cannot be used for persistent storage using this mechanism.
PHPExcel_CachedObjectStorageFactory::cache_to_wincache;
When using cache_to_wincache, cell objects are maintained in Wincache[ You must have Wincache enabled for PHP to use this option.] with only an index maintained in PHP memory to identify that the cell exists. By default, a Wincache cache timeout of 600 seconds is used, which should be enough for most applications: although it is possible to change this when initialising cache_to_wincache.
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_wincache;
$cacheSettings = array( 'cacheTime'        => 600
                      );
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
When your script terminates all entries will be cleared from Wincache, regardless of the cacheTime value, so it cannot be used for persistent storage using this mechanism.
PHPExcel_CachedObjectStorageFactory::cache_to_sqlite;
Uses an SQLite 2 in-memory database for caching cell data. Unlike other caching methods, neither cells nor an index are held in PHP memory - an indexed database table makes it unnecessary to hold any index in PHP memory – making this the most memory-efficient of the cell caching methods.
PHPExcel_CachedObjectStorageFactory::cache_to_sqlite3;
Uses an SQLite 3 in-memory database for caching cell data. Unlike other caching methods, neither cells nor an index are held in PHP memory - an indexed database table makes it unnecessary to hold any index in PHP memory – making this the most memory-efficient of the cell caching methods.

4.2.2.Language/Locale
Some localisation elements have been included in PHPExcel. You can set a locale by changing the settings. To set the locale to Brazilian Portuguese you would use:

$locale = 'pt_br';
$validLocale = PHPExcel_Settings::setLocale($locale);
if (!$validLocale) {
	echo 'Unable to set locale to '.$locale." - reverting to en_us<br />\n";
}

If Brazilian Portuguese language files aren’t available, then the Portuguese will be enabled instead: if Portuguese language files aren’t available, then the setLocale() method will return an error, and American English (en_us) settings will be used throughout.
More details of the features available once a locale has been set, including a list of the languages and locales currently supported, can be found in section 4.5.5 Locale Settings for Formulae.
4.3.Clearing a Workbook from memory
The PHPExcel object contains cyclic references (e.g. the workbook is linked to the worksheets, and the worksheets are linked to their parent workbook) which cause problems when PHP tries to clear the objects from memory when they are unset(), or at the end of a function when they are in local scope. The result of this is “memory leaks”, which can easily use a large amount of PHP’s limited memory.
This can only be resolved manually: if you need to unset a workbook, then you also need to “break” these cyclic references before doing so. PHPExcel provides the disconnectWorksheets() method for this purpose.

$objPHPExcel->disconnectWorksheets();
unset($objPHPExcel);

4.4.Worksheets
A worksheet is a collection of cells, formula’s, images, graphs, … It holds all data necessary to represent as a spreadsheet worksheet.

When you load a workbook from a spreadsheet file, it will be loaded with all its existing worksheets (unless you specified that only certain sheets should be loaded). When you load from non-spreadsheet files (such as a CSV or HTML file) or from spreadsheet formats that don’t identify worksheets by name (such as SYLK), then a single worksheet called “WorkSheet” will be created containing the data from that file.
When you instantiate a new workbook, PHPExcel will create it with a single worksheet called “WorkSheet”.
The getSheetCount() method will tell you the number of worksheets in the workbook; while the getSheetNames() method will return a list of all worksheets in the workbook, indexed by the order in which their “tabs” would appear when opened in MS Excel (or other appropriate Spreadsheet program).

Individual worksheets can be accessed by name, or by their index position in the workbook. The index position represents the order that each worksheet “tab” is shown when the workbook is opened in MS Excel (or other appropriate Spreadsheet program). To access a sheet by its index, use the getSheet() method.

// Get the second sheet in the workbook
// Note that sheets are indexed from 0
$objPHPExcel->getSheet(1);

If you don’t specify a sheet index, then the first worksheet will be returned.

Methods also exist allowing you to reorder the worksheets in the workbook.

To access a sheet by name, use the getSheetByName() method, specifying the name of the worksheet that you want to access.

// Retrieve the worksheet called 'Worksheet 1'
$objPHPExcel->getSheetByName('Worksheet 1');

Alternatively, one worksheet is always the currently active worksheet, and you can access that directly. The currently active worksheet is the one that will be active when the workbook is opened in MS Excel (or other appropriate Spreadsheet program).

// Retrieve the current active worksheet
$objPHPExcel->getActiveSheet();

You can change the currently active sheet by index or by name using the setActiveSheetIndex() and setActiveSheetIndexByName()methods.
4.4.1.Adding a new Worksheet
You can add a new worksheet to the workbook using the createSheet() method of the PHPExcel object. By default, this will be created as a new “last” sheet; but you can also specify an index position as an argument, and the worksheet will be inserted at that position, shuffling all subsequent worksheets in the collection down a place.

$objPHPExcel->createSheet();

A new worksheet created using this method will be called “Worksheet” or “Worksheet<n>” where “<n>” is the lowest number possible to guarantee that the title is unique.

Alternatively, you can instantiate a new worksheet (setting the title to whatever you choose) and then insert it into your workbook using the addSheet() method.

// Create a new worksheet called “My Data”
$myWorkSheet = new PHPExcel_Worksheet($objPHPExcel, 'My Data');
// Attach the “My Data” worksheet as the first worksheet in the PHPExcel object
$objPHPExcel->addSheet($myWorkSheet, 0);

If you don’t specify an index position as the second argument, then the new worksheet will be added after the last existing worksheet.
4.4.2.Copying Worksheets
Sheets within the same workbook can be copied by creating a clone of the worksheet you wish to copy, and then using the addSheet() method to insert the clone into the workbook.

$objClonedWorksheet = clone $objPHPExcel->getSheetByName('Worksheet 1');
$objClonedWorksheet->setTitle('Copy of Worksheet 1')
$objPHPExcel->addSheet($objClonedWorksheet);

You can also copy worksheets from one workbook to another, though this is more complex as PHPExcel also has to replicate the styling between the two workbooks. The addExternalSheet() method is provided for this purpose.

$objClonedWorksheet = clone $objPHPExcel1->getSheetByName('Worksheet 1');
$objPHPExcel->addExternalSheet($objClonedWorksheet);

In both cases, it is the developer’s responsibility to ensure that worksheet names are not duplicated. PHPExcel will throw an exception if you attempt to copy worksheets that will result in a duplicate name.
4.4.3.Removing a Worksheet
You can delete a worksheet from a workbook, identified by its index position, using the removeSheetByIndex() method

$sheetIndex = $objPHPExcel->getIndex($objPHPExcel-> getSheetByName('Worksheet 1'));
$objPHPExcel->removeSheetByIndex($sheetIndex);

If the currently active worksheet is deleted, then the sheet at the previous index position will become the currently active sheet.
4.5.Accessing cells
Accessing cells in a PHPExcel worksheet should be pretty straightforward. This topic lists some of the options to access a cell.
4.5.1.Setting a cell value by coordinate
Setting a cell value by coordinate can be done using the worksheet’s setCellValue() method.

// Set cell A1 with a string value
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'PHPExcel');

// Set cell A2 with a numeric value
$objPHPExcel->getActiveSheet()->setCellValue('A2', 12345.6789);

// Set cell A3 with a boolean value
$objPHPExcel->getActiveSheet()->setCellValue('A3', TRUE);

// Set cell A4 with a formula
$objPHPExcel->getActiveSheet()->setCellValue(
    'A4', 
    '=IF(A3, CONCATENATE(A1, " ", A2), CONCATENATE(A2, " ", A1))'
);

Alternatively, you can retrieve the cell object, and then call the cell’s setValue() method:

$objPHPExcel->getActiveSheet()
    ->getCell('B8')
    ->setValue('Some value');

Excel DataTypes
MS Excel supports 7 basic datatypes
string
number
boolean
null
formula
error
Inline (or rich text) string

By default, when you call the worksheet’s setCellValue() method or the cell’s setValue() method, PHPExcel will use the appropriate datatype for PHP nulls, booleans, floats or integers; or cast any string data value that you pass to the method into the most appropriate datatype, so numeric strings will be cast to numbers, while string values beginning with “=” will be converted to a formula. Strings that aren’t numeric, or that don’t begin with a leading “=” will be treated as genuine string values.

This “conversion” is handled by a cell “value binder”, and you can write custom “value binders” to change the behaviour of these “conversions”. The standard PHPExcel package also provides an “advanced value binder” that handles a number of more complex conversions, such as converting strings with a fractional format like “3/4” to a number value (0.75 in this case) and setting an appropriate “fraction” number format mask. Similarly, strings like “5%” will be converted to a value of 0.05, and a percentage number format mask applied, and strings containing values that look like dates will be converted to Excel serialized datetimestamp values, and a corresponding mask applied. This is particularly useful when loading data from csv files, or setting cell values from a database.

Formats handled by the advanced value binder include
TRUE or FALSE (dependent on locale settings) are converted to booleans.
Numeric strings identified as scientific (exponential) format are converted to numbers.
Fractions and vulgar fractions are converted to numbers, and an appropriate number format mask applied.
Percentages are converted to numbers, divided by 100, and an appropriate number format mask applied.
Dates and times are converted to Excel timestamp values (numbers), and an appropriate number format mask applied.
When strings contain a newline character ("\n"), then the cell styling is set to wrap.

You can read more about value binders later in section 4.5.6 (“Using value binders to facilitate data entry”) of this document.

Setting a date and/or time value in a cell
Date or time values are held as timestamp in Excel (a simple floating point value), and a number format mask is used to show how that value should be formatted; so if we want to store a date in a cell, we need to calculate the correct Excel timestamp, and set a number format mask.

// Get the current date/time and convert to an Excel date/time
$dateTimeNow = time();
$excelDateValue = PHPExcel_Shared_Date::PHPToExcel( $dateTimeNow );
// Set cell A6 with the Excel date/time value
$objPHPExcel->getActiveSheet()->setCellValue(
    'A6', 
    $excelDateValue
);
// Set the number format mask so that the excel timestamp will be displayed
//     as a human-readable date/time
$objPHPExcel->getActiveSheet()->getStyle('A6')
    ->getNumberFormat()
    ->setFormatCode(
        PHPExcel_Style_NumberFormat::FORMAT_DATE_DATETIME
    );

Setting a number with leading zeroes
By default, PHPExcel will automatically detect the value type and set it to the appropriate Excel numeric datatype. This type conversion is handled by a value binder, as described in the section of this document entitled “Using value binders to facilitate data entry”.

Numbers don’t have leading zeroes, so if you try to set a numeric value that does have leading zeroes (such as a telephone number) then these will be normally be lost as the value is cast to a number, so “01513789642” will be displayed as 1513789642.

There are two ways you can force PHPExcel to override this behaviour.

Firstly, you can set the datatype explicitly as a string so that it is not converted to a number.

// Set cell A8 with a numeric value, but tell PHPExcel it should be treated
//     as a string
$objPHPExcel->getActiveSheet()->setCellValueExplicit(
    'A8', 
    "01513789642",
    PHPExcel_Cell_DataType::TYPE_STRING
);

Alternatively, you can use a number format mask to display the value with leading zeroes.

// Set cell A9 with a numeric value
$objPHPExcel->getActiveSheet()->setCellValue('A9', 1513789642);
// Set a number format mask to display the value as 11 digits with leading zeroes
$objPHPExcel->getActiveSheet()->getStyle('A9')
    ->getNumberFormat()
    ->setFormatCode(
        '00000000000'
    );

With number format masking, you can even break up the digits into groups to make the value more easily readable.

// Set cell A10 with a numeric value
$objPHPExcel->getActiveSheet()->setCellValue('A10', 1513789642);
// Set a number format mask to display the value as 11 digits with leading zeroes
$objPHPExcel->getActiveSheet()->getStyle('A10')
    ->getNumberFormat()
    ->setFormatCode(
        '0000-000-0000'
    );



Note that not all complex format masks such as this one will work when retrieving a formatted value to display “on screen”, or for certain writers such as HTML or PDF, but it will work with the true spreadsheet writers (Excel2007 and Excel5).
4.5.2.Setting a range of cells from an array

It is also possible to set a range of cell values in a single call by passing an array of values to the fromArray() method.

$arrayData = array(
    array(NULL, 2010, 2011, 2012),
    array('Q1',   12,   15,   21),
    array('Q2',   56,   73,   86),
    array('Q3',   52,   61,   69),
    array('Q4',   30,   32,    0),
);
$objPHPExcel->getActiveSheet()
    ->fromArray(
        $arrayData,  // The data to set
        NULL,        // Array values with this value will not be set
        'C3'         // Top left coordinate of the worksheet range where
                     //    we want to set these values (default is A1)
    );



If you pass a 2-d array, then this will be treated as a series of rows and columns. A 1-d array will be treated as a single row, which is particularly useful if you're fetching an array of data from a database.

$rowArray = array('Value1', 'Value2', 'Value3', 'Value4');
$objPHPExcel->getActiveSheet()
    ->fromArray(
        $rowArray,   // The data to set
        NULL,        // Array values with this value will not be set
        'C3'         // Top left coordinate of the worksheet range where
                     //    we want to set these values (default is A1)
    );



If you have a simple 1-d array, and want to write it as a column, then the following will convert it into an appropriately structured 2-d array that can be fed to the `fromArray()` method:

$rowArray = array('Value1', 'Value2', 'Value3', 'Value4');
$columnArray = array_chunk($rowArray, 1);
$objPHPExcel->getActiveSheet()
    ->fromArray(
        $columnArray,   // The data to set
        NULL,           // Array values with this value will not be set
        'C3'            // Top left coordinate of the worksheet range where
                        //    we want to set these values (default is A1)
    );



4.5.3.Retrieving a cell by coordinate
To retrieve the value of a cell, the cell should first be retrieved from the worksheet using the getCell() method. A cell’s value can be read again using the following line of code:

$objPHPExcel->getActiveSheet()->getCell('B8')->getValue();

If you need the calculated value of a cell, use the following code. This is further explained in 4.4.35.

$objPHPExcel->getActiveSheet()->getCell('B8')->getCalculatedValue();
4.5.4.Setting a cell value by column and row
Setting a cell value by coordinate can be done using the worksheet’s setCellValueByColumnAndRow() method.

// Set cell B8
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, 8, 'Some value');
4.5.5.Retrieving a cell by column and row
To retrieve the value of a cell, the cell should first be retrieved from the worksheet using the getCellByColumnAndRow() method. A cell’s value can be read again using the following line of code:

// Get cell B8
$objPHPExcel->getActiveSheet()->getCellByColumnAndRow(1, 8)->getValue();

If you need the calculated value of a cell, use the following code. This is further explained in section 4.4.35

// Get cell B8
$objPHPExcel->getActiveSheet()->getCellByColumnAndRow(1, 8)->getCalculatedValue();
4.5.6.Looping cells
Looping cells using iterators
The easiest way to loop cells is by using iterators. Using iterators, one can use foreach to loop worksheets, rows and cells.

Below is an example where we read all the values in a worksheet and display them in a table.

</pre>

	<p>我的第一个段落。</p>
	 
	</body>
	</html>
